<template>
  <div id="components-form-demo-vuex">
    <a-form :form="form" @submit.prevent="handleSubmit">
      <a-form-item label="群组名称">
        <a-input
          v-decorator="[
            'group_name',
            {
              rules: [{ required: true, message: '群组名称!' }],
            },
          ]"
        />
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { addGroup } from '@/api/flow/group'

export default {
  data () {
    return {
      // form
      form: this.$form.createForm(this),

      // state
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
      },
    }
  },

  methods: {
    handleSubmit () {
      const { state } = this

      state.loginBtn = true

      return new Promise((resolve, reject) => {
        this.validateFieldsForm()
          .then(() => {
            this.submitForm()
              .then(async (data) => {
                try {
                  state.loginBtn = false
                  resolve(data)
                } catch (error) {
                  state.loginBtn = false
                  reject(error)
                }
              })
              .catch((error) => {
                reject(error)
              })
              .finally(() => {
                state.loginBtn = false
              })
          })
          .catch((error) => {
            reject(error)
            state.loginBtn = false
          })
      })
    },

    submitCallBack () {
    },

    resetFields () {
      this.form.resetFields()
    },

    // form validateFields
    validateFieldsForm () {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFields },
        } = this

        const validateFieldsKey = ['group_name']

        validateFields(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve()
            return false
          }
          reject(false)
        })
      })
    },

    // Retrieve password
    submitForm () {
      const validateFieldsKey = ['group_name']

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey)

        addGroup(fields)
          .then((data) => {
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
  },
}
</script>
<style>
</style>
